<script setup lang="ts">
import {
  showFailToast,
  type FieldRule,
  type FormInstance,
  showSuccessToast,
  showConfirmDialog
} from 'vant'
import { watch } from 'vue'
import { ref } from 'vue'
import type { patientAddReq, patientUpdateReq } from '@/types/user'
import { patientAdd, patientUpdate, patientDel } from '@/api/user'
const emits = defineEmits<{
  (e: 'getData'): void
}>()
// 用于区分场景的mode  add:新增  edit:编辑
const mode = ref('add')
const show = ref(false)
const options = [
  { label: '男', value: 1 },
  { label: '女', value: 0 }
]
const gender = ref(0)
// 导航栏返回
const backEvent = () => {
  show.value = false
}
// 表单处理
const formData = ref<patientAddReq>({
  name: '张三',
  idCard: '110101196107145504',
  defaultFlag: 0,
  gender: 0
})
const defaultFlag = ref(false)
// watch:侦听某些数据的变化
//  const stop=watch('需要侦听的数据/[需要侦听数据a,b]/()=>响应式数据的.某属性的值',(newVal,oldVal)=>{},{deep,immediate,flush:pre:渲染前执行回调,post:渲染后执行回调，sync:修改一次执行一次回调（渲染前）})
watch(
  defaultFlag,
  newVal => {
    // newVal  true    defaultFlag=1
    // newVal  false   defaultFlag=0
    formData.value.defaultFlag = newVal ? 1 : 0
  },
  {
    immediate: true
  }
)

const rules = {
  name: [
    { required: true, message: '必填', trigger: 'onChange' },
    { pattern: /^.{2,18}$/, message: '请输入2-18位的姓名', trigger: 'onChange' }
  ] as FieldRule[],
  idCard: [
    { required: true, message: '必填', trigger: 'onChange' },
    {
      pattern:
        /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/,
      message: '请正确输入身份证号',
      trigger: 'onChange'
    }
  ] as FieldRule[]
}
const form = ref<FormInstance>()
const checkGender = () => {
  const result = +formData.value.idCard.slice(-2, -1) % 2
  if (result !== formData.value.gender) {
    showFailToast('性别与身份证号不符')
    return false
  }
  return true
}
const save = async () => {
  await form.value?.validate()
  // 验证性别不敢出来身份证号是否匹配
  if (!checkGender()) {
    return
  }
  // 调用新增api
  if (mode.value === 'add') {
    await patientAdd(formData.value)
    // 新增成功:
    // 1:提示
    showSuccessToast('新增成功')
    console.log(formData.value)
  } else if (mode.value === 'edit') {
    console.log(formData.value)
    const { name, idCard, defaultFlag, id, gender } = formData.value
    await patientUpdate({ name, idCard, defaultFlag, id, gender } as patientUpdateReq)
    // 1:提示
    showSuccessToast('编辑成功')
  }
  // 2:关闭弹框
  show.value = false
  // 3:清空表单数据
  formData.value = {
    name: '张三',
    idCard: '110101196107145504',
    defaultFlag: 0,
    gender: 0
  }
  // 刷新父级列表
  emits('getData')
}
// 删除事件
const delEvent = async () => {
  await showConfirmDialog({
    title: '提示',
    message: '您确定删除该项吗？'
  })
  await patientDel(formData.value.id!)
  showSuccessToast('删除成功')
  show.value = false
  // 3:清空表单数据
  formData.value = {
    name: '张三',
    idCard: '110101196107145504',
    defaultFlag: 0,
    gender: 0
  }
  emits('getData')
}

defineExpose({
  show,
  mode,
  formData,
  defaultFlag
})
</script>

<template>
  <div class="add">
    <van-popup v-model:show="show" position="right">
      <cp-nav-bar
        :title="{ add: '新增患者', edit: '编辑患者' }[mode]"
        right-text="保存"
        :back="backEvent"
        @rightClick="save"
      ></cp-nav-bar>
      <van-form autocomplete="off" ref="form">
        <van-field
          label="真实姓名"
          :rules="rules.name"
          v-model="formData.name"
          placeholder="请输入真实姓名"
        />
        <van-field
          label="身份证号"
          :rules="rules.idCard"
          v-model="formData.idCard"
          placeholder="请输入身份证号"
        />
        <van-field label="性别" class="pb4">
          <!-- 单选按钮组件 -->
          <template #input>
            <cp-radio-btn :options="options" v-model="formData.gender"></cp-radio-btn>
          </template>
        </van-field>
        <van-field label="默认就诊人">
          <template #input>
            <van-checkbox v-model="defaultFlag" :icon-size="18" round />
          </template>
        </van-field>
      </van-form>

      <van-button class="del" v-if="mode === 'edit'" @click="delEvent">删除</van-button>
    </van-popup>
  </div>
</template>

<style lang="scss" scoped>
.add {
  :deep {
    .van-popup {
      width: 100% !important;
      height: 100% !important;
      padding-top: 46px;
      box-sizing: border-box;
    }
  }
}
.del {
  width: 100%;
  color: red;
}
</style>
